//
//  HomeViewController.m
//  e-Learning
//
//  Created by rimi on 16/6/16.
//  Copyright © 2016年 YJ. All rights reserved.
//

#import "HomeViewController.h"
#import "iCarousel.h"

@interface HomeViewController ()<UIWebViewDelegate,iCarouselDataSource,iCarouselDelegate,UITextViewDelegate>
{
    UIView *mainContainerVu;
    UIView *detailContainerVu;
    NSArray *newsClassArray;
    NSArray *newsScrollArray;
    NSMutableArray *topNewsIdArray;
    NSMutableArray *topNewsArray;
}
@property (nonatomic,strong) iCarousel *topScrollVu;
@property (nonatomic,strong) UIScrollView *bottomScrollVu;
@property (nonatomic,strong) UIWebView *webVu;
@property (nonatomic,strong) UIButton *backBtn;

@end


@implementation HomeViewController


#pragma mark - LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    mainContainerVu = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    //因为用的懒加载 还是之前在内存里面在的 top bottomVu 所以回来是原来的图形. 虽然容器视图换了. 但是容量视图上的内容并没有换;
    [mainContainerVu addSubview:self.topScrollVu];
    [mainContainerVu addSubview:self.bottomScrollVu];
    [self.view addSubview:mainContainerVu];
    [self dealTopScrollVu];
    [self dealBottomScrollVu];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [mainContainerVu removeFromSuperview];
    mainContainerVu = nil;
    [detailContainerVu removeFromSuperview];
    detailContainerVu = nil;
}

#pragma mark - ActionEvents

- (void)dealTopScrollVu{
    //头部新闻请求
    topNewsIdArray = [@[] mutableCopy];
    topNewsArray = [@[] mutableCopy];
    [[NetWorkTools sharedTools] requestMethod:POST URL:url(@"front_home!news.action") parameters:nil finish:^(id responseObject, NSError *error) {
        newsScrollArray = responseObject[@"data"];
        [self scroll3D];
    }];
}

- (void)dealBottomScrollVu{
    //底部班级请求
    //content点进去的图,img外面的图
    [[NetWorkTools sharedTools] requestMethod:GET URL:url(@"front_home!classInfo.action") parameters:nil finish:^(id responseObject, NSError *error) {
        
        newsClassArray = responseObject[@"data"];
        [self classInfo];
        
    }];
    
    //底部web
    [[NetWorkTools sharedTools] requestMethod:GET URL:url(@"front_home!centerInfo.action") parameters:nil finish:^(id responseObject, NSError *error) {
        
        NSString * webStr = responseObject[@"data"];
        [self webbbbbb:webStr];
        
    }];
    
}


- (void)scroll3D{
    //头部新闻信息处理
    for (int i = 0; i < newsScrollArray.count; i ++) {
        [topNewsIdArray addObject:newsScrollArray[i][@"id"]];
        UIImageView *topNewsImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width/2, Screen_Height/9*7/2*0.8)];
        [topNewsImage sd_setImageWithURL:[NSURL URLWithString:url(newsScrollArray[i][@"img"])] placeholderImage:[UIImage imageNamed:@"enjoy_添加图片.png"] options:SDWebImageProgressiveDownload completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            [topNewsArray addObject:topNewsImage];
                if (i == newsScrollArray.count-1) {
                    self.topScrollVu.dataSource = self;
                    self.topScrollVu.delegate = self;
                }
        }];
    }
}

- (void)topNewsInfo:(NSInteger)index{
    //头部滚动新闻
    [self mainVuEnterDetailVu];
    
    [[NetWorkTools sharedTools] requestMethod:POST URL:sid(url(@"front_home!newsDetail.action")) parameters:@{@"id":topNewsIdArray[index],@"token":[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]} finish:^(id responseObject, NSError *error) {
        if ([responseObject[@"status"] intValue] == 104) {
            //重复登陆处理
 
        } else if ([responseObject[@"status"] intValue] == 1){
            //请求成功
            UIWebView *detailWebVu = [[UIWebView alloc] initWithFrame:CGRectMake(0, Screen_Height/9, Screen_Width, Screen_Height/9*7)];
            NSString *dealString =[responseObject[@"data"][@"content"]  stringByReplacingOccurrencesOfString:@"font-size: 16px;" withString:@"font-size: 22px;"];
            dealString = [dealString stringByReplacingOccurrencesOfString:@"font-size: 18px;" withString:@"font-size: 25px;"];
            dealString = [dealString stringByReplacingOccurrencesOfString:@"line-height: 1.75em;" withString:@"line-height: 2.30em;"];
            dealString = [dealString stringByReplacingOccurrencesOfString:@"font-family: 微软雅黑;" withString:@"font-family: 微软雅黑; font-size: 24px;"];
            dealString = [dealString stringByReplacingOccurrencesOfString:@"line-height: 38.5px;" withString:@"line-height: 48.5px;"];
            dealString = [dealString stringByReplacingOccurrencesOfString:@"font-size: 14px; line-height: 24px;" withString:@"font-size: 22px; line-height: 38px;"];
            [detailWebVu loadHTMLString:dealString baseURL:nil];
            detailWebVu.backgroundColor = [UIColor whiteColor];
            [detailContainerVu insertSubview:detailWebVu belowSubview:self.backBtn];
        }
    }];
}

- (void)classInfo{
    //创建中间的班级信息
    for (int i = 0; i < newsClassArray.count; i ++) {
        UIView *vu = [[UIView alloc] initWithFrame:CGRectMake(Screen_Width/40+Screen_Width/4*i, 0, Screen_Width/4-Screen_Width/20, Screen_Height/9*7/2/7*3)];
        
        CustomBtn *btn =[[CustomBtn alloc] initWithFrame:CGRectMake((CGRectGetWidth(vu.frame)-CGRectGetHeight(vu.frame)/5*3)/2, 0, CGRectGetHeight(vu.frame)/5*3, CGRectGetHeight(vu.frame)/5*3) index:i];
        [btn sd_setImageWithURL:[NSURL URLWithString:url(newsClassArray[i][@"img"])] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"default_head_s.png"] options:SDWebImageProgressiveDownload];
        [btn addTarget:self action:@selector(newsBtn:) forControlEvents:UIControlEventTouchUpInside];
        [vu addSubview:btn];
        
        
        UITextView *textVu = [[UITextView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(vu.frame)/5*3+5, CGRectGetWidth(vu.frame), CGRectGetHeight(vu.frame)/5*2-5)];
        textVu.delegate = self;
        textVu.text = newsClassArray[i][@"name"];
        if (Screen_Width >= 1366) {
            textVu.font = [UIFont systemFontOfSize:21];
        } else {
            textVu.font = [UIFont systemFontOfSize:16];
        }
        textVu.textAlignment = NSTextAlignmentCenter;
        [vu addSubview:textVu];
        [self.bottomScrollVu addSubview:vu];
        
    }
    //加个线条
    UIView *grayLine = [[UIView alloc] initWithFrame:CGRectMake(Screen_Width/30, Screen_Height/9*7/2/7*3+20, Screen_Width/30*28, 1.5)];
    grayLine.backgroundColor = [UIColor lightGrayColor];
    [self.bottomScrollVu addSubview:grayLine];

}

- (void)newsBtn:(CustomBtn *)sender{
    [self mainVuEnterDetailVu];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"数据加载中\n请稍候" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    
    UIImageView *detailVu = [[UIImageView alloc] initWithFrame:CGRectMake((Screen_Width-Screen_Width/3)/2, Screen_Height/9, Screen_Width/3, Screen_Width/3)];
    [detailContainerVu addSubview:detailVu];
    
    [detailVu sd_setImageWithURL:[NSURL URLWithString:url(newsClassArray[sender.index][@"content"])] placeholderImage:nil options:SDWebImageProgressiveDownload completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [alert dismissViewControllerAnimated:YES completion:nil];
    }];
    //添加返回按钮
    [self createBackBtn];
}


- (void)detailBack:(UIButton *)sender{
    for (int i = 0; i < detailContainerVu.subviews.count; i ++) {
        if (![detailContainerVu.subviews[i] isKindOfClass:[UIButton class]]) {
            [detailContainerVu.subviews[i] removeFromSuperview];
        }
    }
    [detailContainerVu removeFromSuperview];
    detailContainerVu = nil;
    [self.view addSubview:mainContainerVu];
    
}

- (void)webbbbbb:(NSString *)str{
    
    NSString *dealStr = [str stringByReplacingOccurrencesOfString:@"<span style=\"box-sizing: border-box;\">" withString:@"<span style=\"box-sizing: border-box;font-size:22px;\">"];
    NSString *finalStr = [dealStr stringByReplacingOccurrencesOfString:@"max-width: 100%; height: auto;" withString:[[[@"max-width: " stringByAppendingFormat:@"%f",Screen_Width/4*3] stringByAppendingString:@"px; "] stringByAppendingString: [[@"height: " stringByAppendingFormat:@"%f",Screen_Width/4*3/3*2] stringByAppendingString:@"px; "]]];
    
    [self.webVu loadHTMLString:finalStr baseURL:nil];
    [self.bottomScrollVu addSubview:self.webVu];
   
}

- (void)createBackBtn{
    int i;
    for (i = 0; i < detailContainerVu.subviews.count; i ++) {
        if ([detailContainerVu.subviews[i] isKindOfClass:[UIButton class]]) {
            return;
        }
    }
    if (i == detailContainerVu.subviews.count) {
        [detailContainerVu addSubview:self.backBtn];
    }
}

- (void)mainVuEnterDetailVu{
    [mainContainerVu removeFromSuperview];
    if (!detailContainerVu) {
        detailContainerVu = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    [self.view addSubview:detailContainerVu];

}

#pragma mark - iCarouselDataSource,iCarouselDelegate

- (NSInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
    return topNewsArray.count;
}

- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view{
    return topNewsArray[index];
}

- (CGFloat)carouselItemWidth:(iCarousel *)carousel
{
    return Screen_Width/2;
}



- (CATransform3D)carousel:(iCarousel *)_carousel transformForItemView:(UIView *)view withOffset:(CGFloat)offset
{
    CATransform3D transform = CATransform3DIdentity;
    transform.m34 = self.topScrollVu.perspective;
    transform = CATransform3DRotate(transform, M_PI / 8.0, 0, 1.0, 0);
    return CATransform3DTranslate(transform, 0.0, 0.0, offset * self.topScrollVu.itemWidth);
}

- (CGFloat)carousel:(iCarousel *)carousel valueForOption:(iCarouselOption)option withDefault:(CGFloat)value{
    if (option == iCarouselOptionWrap) {
        return 1;
    }
    if (option == iCarouselOptionVisibleItems){
        return 3;
    }
    return value;
}

- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index{
    [mainContainerVu removeFromSuperview];
    if (!detailContainerVu) {
        detailContainerVu = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    [self.view addSubview:detailContainerVu];
    [self createBackBtn];
    [self topNewsInfo:index];
}

#pragma mark - UITextViewDelegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    return NO;
}

#pragma mark - UIWebViewDelegate

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    //webView:frame
    CGFloat webViewHeight= [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
    self.bottomScrollVu.contentSize = CGSizeMake(Screen_Width, webViewHeight+Screen_Height/9*7/2/7*3+Screen_Width/9);
    webView.frame =  CGRectMake(Screen_Width/30, Screen_Height/9*7/2/7*3+40, Screen_Width/4*3, webViewHeight);
    
    //二维码
    UIImageView *code = [[UIImageView alloc] initWithFrame:CGRectMake((Screen_Width-CGRectGetMaxX(webView.frame)-Screen_Width/4/4*3)/2+CGRectGetMaxX(webView.frame), Screen_Height/9*7/2/7*3+40, Screen_Width/4/4*3, Screen_Width/4/4*3)];
    code.backgroundColor = [UIColor redColor];
    code.image = [UIImage imageNamed:@"home_二维码.jpg"];
    [self.bottomScrollVu addSubview:code];
    
    //二维码名称
    UILabel *codeName = [[UILabel alloc] initWithFrame:CGRectMake((Screen_Width-CGRectGetMaxX(webView.frame)-Screen_Width/4/4*3)/2+CGRectGetMaxX(webView.frame), Screen_Height/9*7/2/7*3+40 + Screen_Width/4/4*3, Screen_Width/4/4*3, Screen_Width/4/10)];
    codeName.text = @"西南教大教育培训中心";
    codeName.textAlignment = NSTextAlignmentCenter;
    if (Screen_Width >= 1366) {
        codeName.font = [UIFont systemFontOfSize:22];
    } else {
        codeName.font = [UIFont systemFontOfSize:17];
    }
    [self.bottomScrollVu addSubview:codeName];
}

#pragma mark - Getter

- (iCarousel *)topScrollVu {
    if (!_topScrollVu) {
        _topScrollVu = [[iCarousel alloc] initWithFrame:CGRectMake(0, Screen_Height/9, Screen_Width, Screen_Height/9*7/2)];
        _topScrollVu.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"home_AD_bg.png"]];
        _topScrollVu.type = iCarouselTypeCoverFlow;
    }
    return _topScrollVu;
}

- (UIScrollView *)bottomScrollVu{
    if (!_bottomScrollVu) {
        _bottomScrollVu = [[UIScrollView alloc] initWithFrame:CGRectMake(0, Screen_Height/9+Screen_Height/9*7/2+20, Screen_Width, Screen_Height/9*7/2-20)];
        _bottomScrollVu.contentSize = CGSizeMake(Screen_Width, Screen_Height*3+Screen_Height/5*2);
        _bottomScrollVu.backgroundColor = [UIColor whiteColor];
        
    }
    return _bottomScrollVu;
}

- (UIWebView *)webVu{
    if (!_webVu) {
        _webVu = [[UIWebView alloc] initWithFrame:CGRectZero];
        _webVu.delegate = self;
        _webVu.scrollView.scrollEnabled = NO;
    }
    return _webVu;
}

- (UIButton *)backBtn{
    if (!_backBtn) {
        _backBtn = [[UIButton alloc] initWithFrame:CGRectMake(Screen_Height/9/2, Screen_Height/9*6+Screen_Height/9/2, Screen_Height/9, Screen_Height/9)];
        [_backBtn setBackgroundImage:[UIImage imageNamed:@"activity_back.png"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(detailBack:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}

@end
